<template>
    <div v-loading="loading" class="console-page">
        <el-form inline :model="searchForm" class="e-page form-item" spellcheck="false" @submit.native.prevent>
            <el-row class="toolbar">
                <el-col :span="4" style="padding-right: 5px">
                    <el-input v-model="searchForm.username" placeholder="用户名" clearable class="input-auto-resize" />
                </el-col>
                <el-col :span="4" style="padding-right: 5px">
                    <el-input v-model="searchForm.mail" placeholder="邮箱" clearable class="input-auto-resize" />
                </el-col>
                <el-col :span="4" style="padding-right: 5px">
                    <el-select v-model="searchForm.status" clearable placeholder="请选择状态" class="input-auto-resize">
                        <el-option v-for="item in statusSelect" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-col>
                <el-col :span="4" style="padding-right: 5px">
                    <el-select v-model="searchForm.role" clearable placeholder="请选择角色" class="input-auto-resize">
                        <el-option v-for="item in roleSelect" :key="item.value" :label="item.value"
                            :value="item.value" />
                    </el-select>
                </el-col>
                <el-col :span="1" style="padding-right: 5px;text-align: left">
                    <el-button type="primary" @click="searchTable" circle ripple :icon="getIcon('search')"
                        :loading="bt_loading" native-type="submit" class="button-auto-resize" />
                </el-col>
                <el-col :span="7" style="text-align: right" v-permission="$permission.Write | $permission.Execute">
                    <el-button type="danger" :icon="getIcon('SwitchButton')" circle class="button-auto-resize"
                        @click="offline()" confirmTitle="确定下线所有用户?" v-permission="$permission.Execute" />
                    <el-button :icon="getIcon('plus')" circle class="button-auto-resize" @click="openDialog('new')"
                        v-permission="$permission.Write" />
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableData" border header-cell-class-name="el-table-header-cell" cell-class-name="el-table-cell"
            class="e-page table-with-pagination" highlight-current-row>
            <el-table-column prop="username" label="用户名" min-width="150" />
            <el-table-column prop="nickName" label="昵称" min-width="150" />
            <el-table-column prop="mobile" label="手机" :width="fontAutoResize.size_9.value" />
            <el-table-column prop="mail" label="邮箱" min-width="200" />
            <el-table-column prop="status" label="状态" :width="fontAutoResize.size_6.value">
                <template #default="scope">
                    <!-- 状态 -->
                    <el-tag :type="scope.row.status === '1' ? 'primary' : 'danger'" class="input-auto-resize"
                        disable-transitions>
                        {{ scope.row.status === '1' ? '正常' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="uniqueLogin" label="唯一登录" :width="fontAutoResize.size_6.value">
                <template #default="scope">
                    <!-- 状态 -->
                    <el-tag :type="scope.row.uniqueLogin === 1 ? 'info' : 'primary'" class="input-auto-resize"
                        disable-transitions>
                        {{ scope.row.uniqueLogin === 1 ? '是' : '否' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="uniqueLogin" label="允许登陆来源" :width="fontAutoResize.size_8.value">
                <template #default="scope">
                    <!-- 状态 -->
                    <el-tag :type="scope.row.loginFrom === 0 ? 'primary' : 'info'" class="input-auto-resize"
                        disable-transitions>
                        {{ scope.row.loginFrom === 0 ? '不限制' : scope.row.loginFrom === 1 ? '手机端' : '电脑端' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="role" label="角色" min-width="150" />
            <el-table-column prop="token" label="接口Token" width="300">
                <template #default="scope">
                    <!-- 状态 -->
                    <div v-if="scope.row.token">
                        {{ scope.row.token }}
                    </div>
                    <div v-else>
                        <el-button class="get-token" text link @click="getToken(scope.row)"
                            :confirm-title="`确定生成${scope.row.username}的接口Token?`">生成Token</el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="openId" label="微信ID" width="250" />
            <el-table-column prop="point" label="积分" width="150" />
            <el-table-column prop="payCount" label="接口付费次数" width="150" />
            <el-table-column prop="lastSignDate" label="最新签到时间" :width="fontAutoResize.size_11.value" />
            <el-table-column prop="crtTime" label="创建时间" :width="fontAutoResize.size_11.value" />
            <el-table-column prop="updateTime" label="更新时间" :width="fontAutoResize.size_11.value" />
            <el-table-column fixed="right" label="操作" :width="operationWidth" className="operation-column"
                v-permission="$permission.Update | $permission.Execute">
                <template #default="scope">
                    <el-button type="primary" :icon="getIcon('editPen')" circle class="button-auto-resize"
                        @click="openDialog(tableData[scope.$index])" v-permission="$permission.Update" />
                    <el-button type="danger" circle @click="forbidStatus(tableData[scope.$index])"
                        class="button-auto-resize" v-permission="$permission.Update"
                        :icon="scope.row.status === '1' ? getIcon('lock') : getIcon('unlock')" />
                    <el-button type="danger" :icon="getIcon('SwitchButton')" circle class="button-auto-resize"
                        v-permission="$permission.Execute" @click="offline(scope.row.username)"
                        :confirmTitle="`确定下线所有 ${scope.row.username} 用户?`" />
                </template>
            </el-table-column>
        </el-table>
        <div style="height: 50px;">
            <el-pagination background @size-change="SizeChange" @current-change="CurrentChange"
                :current-page="currentPage" :page-sizes="page_sizes" :page-size="page_size"
                layout="total, sizes, prev, pager, next, jumper" prev-text="<上一页" next-text="下一页>" :total="total"
                class="e-page">
            </el-pagination>
        </div>
        <el-dialog title="用户信息" v-model="userinfoDialog" @close="clearUserForm" class="user-dialog" width="50%"
            top="15vh" :show-close="false" append-to-body>
            <el-form :model="modifyUser" ref="modifyUserRef" class="user-form form-auto-resize" spellcheck="false"
                :rules="rules" @submit.native.prevent>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="modifyUser.username" autocomplete="off" class="input-auto-resize"
                        :disabled="adminDisable" />
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="modifyUser.nickName" autocomplete="off" class="input-auto-resize"
                        :disabled="adminDisable" />
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="modifyUser.role" placeholder="请选择" class="input-auto-resize"
                        :disabled="adminDisable" popper-class="normal-poper">
                        <el-option v-for="item in roleSelect" :key="item.value" :label="item.value"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="唯一登录" prop="uniqueLogin">
                    <el-select v-model="modifyUser.uniqueLogin" placeholder="请选择" class="input-auto-resize"
                        popper-class="normal-poper">
                        <el-option v-for="item in uniqueLogin" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="允许登录来源" prop="loginFrom">
                    <el-select v-model="modifyUser.loginFrom" placeholder="请选择" class="input-auto-resize"
                        popper-class="normal-poper">
                        <el-option v-for="item in loginFrom" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="密码" prop="password" :rules="passwordRule">
                    <el-input v-model="modifyUser.password" placeholder="请输入密码" show-password @focus="getCursor"
                        class="input-auto-resize pwd" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span>
                    <el-button @click="userinfoDialog = false" :icon="getIcon('close')" circle
                        class="button-auto-resize" />
                    <el-button type="primary" @click="submitForm" :icon="getIcon('check')" circle :loading="submitUser"
                        class="button-auto-resize" />
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { getIcon } from "@/utils/tools"
import { useElMessage, useSetTableOperationWidth, useDraggable, useModalSize, useRequest } from "@usehook"
import { admin } from "@/utils/constant"
import { fontAutoResize } from "@/utils/setting"

const operationWidth = useSetTableOperationWidth(3)
let tableData = $ref([])
let currentPage = $ref(1)
let page_size = $ref(0)
let total = $ref(0)
let statusSelect = [{ value: '1', label: '正常' }, { value: '0', label: '禁用' }]
let uniqueLogin = [{ value: 1, label: '是' }, { value: 0, label: '否' }]
let loginFrom = [{ value: 0, label: '不限制' }, { value: 1, label: '手机端' }, { value: 2, label: '电脑端' }]
let userinfoDialog = $ref(false)
let modifyUser = $ref({
    sequence: '',
    username: '',
    mobile: '',
    mail: '',
    password: '',
    role: 'normal',
    status: '',
    nickName: '',
    loginFrom: 0,
    uniqueLogin: 1
})
let searchForm = $ref({
    username: '',
    mail: '',
    role: '',
    status: '1'
})
let loading = $ref(false)
let bt_loading = $ref(false)
let adminDisable = $ref(false)
let page_sizes = [10, 30, 50, 100, 200]
let roleSelect = $ref([])
let passwordRule = $ref([])
let submitUser = $ref(false)
const modifyUserRef = $ref(null)
const rules = {
    username: [{ required: true, message: '请输入用户名称', trigger: [] }, { min: 3, message: '用户名称至少3个字符', trigger: "" }],
    nickName: [{ required: true, message: '请输入昵称或描述', trigger: [] }, { min: 1, message: '昵称或描述信息至少1个字符', trigger: "" }, { max: 10, message: '昵称或描述信息最多10个字符', trigger: "" }]
}

const getToken = (row) => {
    useRequest.post({ url: "/user/apiToken", userId: row.sequence }).then(resp => {
        if (resp && resp.status) {
            for (let data of tableData) {
                if (data.sequence === row.sequence) {
                    data.token = resp.data
                    break
                }
            }
        } else {
            useElMessage.error("token生成失败")
        }
    })
}

const getUserData = (params) => {
    loading = true
    bt_loading = true
    useRequest({ url: "/user/list/getData", ...params }).then(resp => {
        if (resp.status) { //0表示成功，1表示失败
            tableData = resp.data
            total = resp.totalRecord
        } else if (resp.message) useElMessage(resp.message)
    }).finally(_ => {
        loading = false
        bt_loading = false
    })
}

const modifyUserInfo = (userInfo) => {
    submitUser = true
    useRequest({ method: "post", ...userInfo }).then(resp => {
        if (resp.status) { //0表示成功，1表示失败
            if (resp.message) useElMessage(resp.message)
            userinfoDialog = false
            refreshTable()
        } else if (resp.message) useElMessage.error(resp.message)
    }).finally(_ => {
        submitUser = false
    })
}

const clearUserForm = () => {
    useModalSize(false)
    setTimeout(() => {
        for (let i in modifyUser) {
            if (i === 'role') {
                modifyUser[i] = 'normal'
            } else {
                modifyUser[i] = ''
            }
        }
        adminDisable = false
    }, 500)
}

const offline = (username) => {
    useRequest.post({ url: "/user/offline", username }).then((resp) => {
        console.log(resp)
    })
}

const searchTable = () => {
    getUserData({
        'search': JSON.stringify(searchForm),
        'limit': page_size,
        'page': 1
    })
    currentPage = 1
}

const refreshTable = () => {
    setTimeout(() => {
        getUserData({
            'search': JSON.stringify(searchForm),
            'limit': page_size,
            'page': currentPage
        })
    }, 10)
}

const getCursor = (event) => {
    setTimeout(function () {
        event.target.setSelectionRange(-1, -1)
    }, 10)
}

const submitForm = () => {
    modifyUserRef.validate((valid) => {
        if (valid) {
            modifyUserInfo({ user: modifyUser, url: '/user/list/modify' })
        } else {
            return false
        }
    })
}

const forbidStatus = (userData) => {
    //防止当前页面为空页码不跳
    if (total - 1 === (currentPage - 1) * page_size && total !== 1 && searchForm.status) {
        currentPage -= 1
    }

    let userInfo = userData
    if (userInfo) {
        modifyUserInfo({
            sequence: userInfo.sequence,
            url: '/user/list/forbid'
        })
    }
}

const clearValidate = () => {
    if (modifyUserRef) {
        modifyUserRef.clearValidate()
    }
}

const openDialog = (userData) => {
    useModalSize()
    clearValidate()
    if (userData === 'new') {
        passwordRule = [{ required: true, message: '请输入密码', trigger: [] },
        { min: 5, message: '密码长度至少5位', trigger: "" }]
    } else {
        passwordRule = []

        if (userData) {
            modifyUser.username = userData.username
            modifyUser.role = userData.role
            modifyUser.mobile = userData.mobile
            modifyUser.mail = userData.mail
            modifyUser.sequence = userData.sequence
            modifyUser.nickName = userData.nickName
            modifyUser.uniqueLogin = userData.uniqueLogin
            modifyUser.loginFrom = userData.loginFrom
        }
        if (userData.username === admin.name) {
            adminDisable = true
        }
    }
    userinfoDialog = true
}

const SizeChange = (val) => {
    getUserData({
        'search': JSON.stringify(searchForm),
        'limit': val,
        'page': currentPage
    })
    page_size = val
}

const CurrentChange = (val) => {
    getUserData({
        'search': JSON.stringify(searchForm),
        'limit': page_size,
        'page': val
    })
    currentPage = val
}

useDraggable(".user-dialog", { handle: ".user-dialog .el-dialog__header", targetExist: () => userinfoDialog, moveCursor: true })

onMounted(() => {
    page_size = page_sizes[1]
    getUserData({
        'search': JSON.stringify(searchForm),
        'limit': page_size,
        'page': currentPage
    })
    useRequest({ url: "/user/role/getData", search: JSON.stringify({}), limit: 500, page: 1 }).then(resp => {
        resp.data.forEach(item => {
            roleSelect.push({ value: item.name })
        })
    })
})
</script>
<style scoped>
:deep(.el-form-item__error) {
    top: 26%;
    right: 40px;
    left: unset;
    font-size: calc(var(--font-size) - 4px);
    pointer-events: none;
}

:deep(.el-radio-button__inner) {
    height: 25px !important;
}

:deep(.admin-info) {
    display: flex;
    align-items: center;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset
}

:deep(input::placeholder) {
    font-family: var(--font-family);
}

:deep(.get-token) {
    color: #5e95ff;
    text-decoration: underline;
    cursor: pointer;
    font-family: inherit;
}

:deep(.el-button) {
    --el-button-hover-link-text-color: #5e95ff
}
</style>


<style>
.user-dialog.el-dialog .el-dialog__body {
    padding: 5px !important;
}

.user-dialog.el-dialog .el-dialog__header {
    border-bottom: 1px solid #e4e7ec;
}

.user-dialog.el-dialog .el-dialog__footer {
    padding: 10px 20px;
    border-top: 1px solid #e4e7ec;
}

.user-dialog.el-dialog .el-dialog__body .el-form-item {
    margin-bottom: 0 !important
}

.user-form.form-auto-resize .el-form-item__label {
    width: calc(var(--font-size)* 5 + 35px);
}
</style>